<template>
  <basic-container>
    <el-dialog title="登录查看文件" width='300px' :visible="shareFileDialog">
      <div style='text-align:center;'>
        <el-form class="login-form"
              status-icon
              :rules="loginRules"
              ref="loginForm"
              :model="loginForm"
              label-width="0">
        <el-form-item prop="username">
          <el-input size="small"
                    @keyup.enter.native="handleLogin"
                    v-model="loginForm.username"
                    auto-complete="off"
                    :placeholder="$t('login.username')">
            <i slot="prefix"
              class="icon-yonghu"></i>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input size="small"
                    @keyup.enter.native="handleLogin"
                    :type="passwordType"
                    v-model="loginForm.password"
                    auto-complete="off"
                    :placeholder="$t('login.password')">
            <i class="el-icon-view el-input__icon"
              slot="suffix"
              @click="showPassword"></i>
            <i slot="prefix"
              class="icon-mima"></i>
          </el-input>
        </el-form-item>
        <el-form-item v-if="captchaMode" prop="code">
          <el-row :span="24">
            <el-col :span="16">
              <el-input size="small"
                        @keyup.enter.native="handleLogin"
                        v-model="loginForm.code"
                        auto-complete="off"
                        :placeholder="$t('login.code')">
                <i slot="prefix" class="icon-yanzhengma"/>
              </el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                    size="small"
                    @click.native.prevent="handleLogin"
                    class="login-submit">{{$t('login.submit')}}
          </el-button>
        </el-form-item>
      </el-form>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getViewUrlDbPath} from '@/api/general/file/wpsApi';
import {saveGeneralFileInfo,queryGeneralFileInfo} from '@/api/general/file/generalFileInfoApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
import {getToken} from '@/util/auth'
import {Base64} from 'js-base64';
import website from '@/config/website';

export default {
  data() {
    return {
      //编辑器名
      officeEditor: 'onlyoffice',
      shareFileDialog: false,
      loginForm: {
        //用户名
        username: 'admin',
        //密码
        password: '123',
        //账户类型
        type: 'account',
        //验证码的值
        code: '',
        //验证码的索引
        key: '',
        //预加载白色背景
      },
      loginRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 1, message: '密码长度最少为6位', trigger: 'blur'}
        ]
      },
      passwordType: 'password',
      // 分享
      tenantId: '',
      fileId: '',
      currentFile: {},
      shareMode: '0',
      mode:0,
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  computed: {
    ...mapGetters(['website','userInfo','orgTree','permission']),
  },
  methods: { 
    /**
     * 查询文件信息
     */
    queryFileInfo(){
      this.reqParams.singleBody = {
        id: this.fileId
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryGeneralFileInfo(this.commonData).then(res => {
        var data = res.data.body.singleBody;
        this.openOfficeDialog(data);
        //this.$console.log('====data===',data);
      }, error => {
        this.$message({
          customClass:'zZindex',
          type: 'error',
          message: '查询记录失败!'
        });
        this.loading=false;
        //this.$console.log(error);
      })
    },
    /**
     * 打开在线编辑窗口
     */
    openOfficeDialog(row){
      let modeStr = 'view';
      if(this.mode == '2'){
        modeStr = 'edit';
      }
      if(this.officeEditor == 'onlyoffice'){
        let openUrl= 'id='+Base64.encode(row.id)+'&tenantId='+Base64.encode(this.userInfo.tenantId)+'&UID='+Base64.encode(this.userInfo.userId)+'&remote=no&UserSign=uploadFile&token='+getToken()+'&mode='+modeStr;
        window.location.href='/file/office/index?'+openUrl+'&sign='+this.$toolUtil.encodeMd5(openUrl); 
      }
      else if(this.officeEditor == 'wps'){
        this.openWps(row)
      }
    },
    /**
     * wps打开文件
     */
    openWps(row){
      //this.loading = true;
      const params = {
        fileId: row.id,
        userId: this.userInfo.userName
      };
      getViewUrlDbPath(params).then((res) => {
        if (res.data) {
          let r = res.data.data;
          this.$console.log('===file url=',r);
          // 跳转 使用sessionStorage，避免关键信息在ip中暴露
          // 使用push会停留当前页面，故不采纳
          // params 传递参数，子组件无法渲染iframe组件，故不采纳
          sessionStorage.wpsUrl = r.wpsUrl;
          sessionStorage.wpstoken = r.token;
          const jump = this.$router.resolve({path: '/viewFile'});
          window.location.href=jump.href;
        }else {
          this.showErrMeg('请求错误！');
        }
        this.loading = false;
      }).catch(()=>{
        this.showErrMeg('请求错误！');
        this.loading = false;
      });
    },
    showPassword() {
      this.passwordType === ''
        ? (this.passwordType = 'password')
        : (this.passwordType = '');
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '登录中,请稍后。。。',
            spinner: 'el-icon-loading'
          });
          this.reqParams = {
            username: this.tenantId+'=user=password=pc=' + this.loginForm.username+'@@password',
            //username: 'pwd='+this.tenantId+'='+this.loginForm.username,
            password: this.$toolUtil.encodeMd5(this.loginForm.password),
            tenantId: this.tenantId
          }
          this.$store.dispatch('LoginByUsername', this.reqParams).then((data) => {
            localStorage.setItem('tenantId', data.additionalInformation.userInfo.tenantId);
            this.$store.dispatch('setUserInfo',data.additionalInformation.userInfo); 
            loading.close();
            this.shareFileDialog = true;
            this.getSysParam();
          }).catch(() => {
            loading.close();
          });
        }
      });
    },
    /**
     * 获取工作日参数
     */
    async getSysParam() {
      let sysParamData = await this.$params.getSysParam('officeEditor');
      if(sysParamData){
        this.officeEditor = sysParamData.officeEditor
      }
      this.queryFileInfo();
    }
  },
  created() {
    let urlParam = this.$toolUtil.UrlSearch();
    if(urlParam.shareNo){
      let shareNo = Base64.decode(urlParam.shareNo.replace(/%3D/g, '='));
      let ids = shareNo.split('||');
      this.tenantId = ids[0];
      this.fileId = ids[1];
      this.mode = ids[2];
      //this.$console.log(this.tenantId +'==== ' + this.fileId)
    }
    else{
      this.tenantId = this.website.defaultTenantId;
    }
    
  },
  mounted() {
    if(!localStorage.getItem('TOKEN') || this.userInfo == null){
      this.shareFileDialog = true;
    }
    else{
      this.shareFileDialog = false;
      //获取系统参数
      setTimeout(() => {
        this.getSysParam();
      }, 100);
    }
    
    //this.queryFileInfo();    
  },
  
};
</script>
<style>
</style>
